<template>
	<view class="bg-white">
		<cu-custom :bgColor="'bg-'+ theme.themeColor" :isBack="true">
			<block slot="content">我的购物车</block>
		</cu-custom>
		<view class="flex justify-between align-center padding-sm bg-white solid-bottom shadow fixed" v-if="shoppingCartList.length">
			<view>
				共{{shoppingCartList.length}}件宝贝
			</view>
			<view>
				<!-- <button class="cu-btn sm" :class="'bg-'+ theme.matchColor"
					@tap="isEdit=!isEdit">
					{{isEdit?'完成' :'编辑'}}
					</button> -->
					 <button class="cu-btn sm" :class="'bg-'+ theme.matchColor" @tap="toggleEditMode">{{ isEdit ? '完成' : '编辑' }}</button>
			</view>
		</view>
		<view style="top: unset !important; margin-top: 90rpx;" class="shopping-cart">
			<checkbox-group @change="checkboxChange">
			        <u-swipe-action :show="item.show" :index="index" v-for="(item, index) in shoppingCartList" :key="index" @click="clickDele(item)" @open="open" :options="options">
							<view class="cu-card solid-bottom padding-sm ">
								<view class="flex align-center">
									<!-- <checkbox class="round margin-lr-xs red" 
										:disabled="item.goodsSku.stock <= 0 && !isEdit" :checked="item.checked" :value="item.id" color="##007aff" style="transform:scale(0.7)">
									</checkbox> -->
									<checkbox ref="checkbox" class="round margin-lr-xs red android" :disabled="item.goodsSku.stock <= 0 && !isEdit" :checked="item.checked"  :value="item.id"   style="transform:scale(0.7);color:#007aff;">
									</checkbox>
									<view @tap="routerLink(item)" hover-class="none" style="width:100%" :disabled="item.goodsSku.stock <= 0">
										<view class="content">
											<view class="flex flex-wrap">
												<view style="width: 30%;height: 102px;position: relative;"
													class="flex align-center justify-center">
													<image :src="item.picUrl" mode="aspectFill" class="margin-top-sm flex-sub"
														style="width: 100%;height: 102px;">
													</image>
													<view v-if="!item.goodsSku || item.goodsSku.stock<=0"
														class="out-stock flex align-center justify-center">
														<text class="text-white">无 货</text>
													</view>
												</view>
						
												<view class="desc padding-left-sm block flex-twice">
													<text class="hx-overflow-2"
														:class="!item.goodsSku || item.goodsSku.stock<=0 ? 'text-gray': 'text-black'">{{item.spuName}}</text>
													<view class="bg-gray radius text-gray margin-top-xs padding-xs"
														v-if="item.specsInfo && item.goodsSku" @tap.stop="openGoodsSku(item)">
														<text class="text-gray text-sm">{{item.specsInfo}}</text>
														<text class="cuIcon-unfold text-gray"></text>
													</view>
													<view class="flex justify-between padding-top-lg">
														<view class="text-price text-bold text-lg"
															:class="!item.goodsSku || item.goodsSku.stock<=0 ? 'text-gray':'text-'+ theme.themeColor">
															{{item.goodsSku.salesPrice}}
														</view>
														<view @tap.stop>
															<view v-if="!item.goodsSku || item.goodsSku.stock<=0">
																<text class="text-bold text-sm"
																	:class="'text-'+theme.themeColor"></text>
															</view>
															<view v-else>
																<uni-number-box :min="1" :max="999" v-model="item.quantity"
																	:disabled="item.quantity == 0 ||  item.quantity>item.goodsSku.stock"
																	@change="numberBoxChange(item)">
																</uni-number-box>
															</view>
						
														</view>
													</view>
												</view>
											</view>
						
										</view>
									</view>
								</view>
							</view>
			        </u-swipe-action>
			</checkbox-group>
			
			<view v-if="shoppingCartList.length<=0" class="margin-top">
				<view class="margin-top flex justify-center">
					<image style="height:153px;width: 144px;" class="margin-top"
						src="/static/image/default/empty-shopping-cart.png" />
				</view>
				<view class="margin-top flex justify-center">
					<navigator hover-class="none" url="/subpkg/goods/goods-list/index">
						<button class="cu-btn margin-top" :class="'bg-'+theme.themeColor">去逛逛</button>
					</navigator>
				</view>
			</view>

		</view>

		<view class="cu-bar justify-center  margin-top-sm">
			<view class="action text-bold" :class="'text-'+theme.themeColor">
				<text class="cuIcon-move"></text> <text class="cuIcon-appreciate"></text>为您推荐<text
					class="cuIcon-move"></text>
			</view>
		</view>
		<goods-list :goodsList="goodsSpuList"></goods-list>
		<!-- 底部操作栏 -->
		<view class="cu-bar bg-white padding-sm foot" v-if="shoppingCartList.length">
			<checkbox-group @change="changeShoppingCartAll">
				<checkbox class="round sm red android" value="selectedAll" :checked="checkedAll" style="transform:scale(0.8)">
				</checkbox><text class="padding-xs">全选</text>
			</checkbox-group>
			<view v-if="isEdit">
				<button class="cu-btn round" @tap="delGoods">删除</button>
			</view>
			<view class="flex align-center" v-else>
				<view class="padding-xs">合计：<text class="text-price text-lg "
						:class="'text-'+ theme.themeColor">{{totalPrice}}</text></view>
				<button class="cu-btn round shadow-blur" :class="'bg-'+ theme.themeColor" @tap="buySub"
					:disabled="showCreateOrder">结算
					{{selectedValueLength > 0 ? '('+selectedValueLength+')':''}}</button>
			</view>
		</view>


		<vk-data-goods-sku-popup v-if="isShow" ref="skuPopup" :shoppingCartId="shoppingCart.id" v-model="skuModal"
			:localdata="goodsSpu" :defaultSelect="selectedSku" skuArrName="goodsSkuSpecsValues" skuListName="goodsSkus"
			specListName="goodsSpuSpecs" @close="skuClose" :mode="modelTpye">
		</vk-data-goods-sku-popup>
	</view>
</template>

<script>
	import {
		getPage as getShoppingCartPage,
		shoppingCartDel,
		shoppingCartEdit
	} from '@/api/shoppingcart.js';
	import {
		getPage as goodsSpuPage,
		getById as goodsSpuById
	} from '@/api/goodsspu.js';
	import GoodsList from "components/goods-list/col-list/index";
	import { getCount } from '@/api/shoppingcart.js'
	import store from '@/store/index' // store
	import badgeMix  from '@/mixins/tabbar-badge.js'
	import debounce from 'lodash/debounce' 
 export default {
	mixins: [badgeMix],
		components: {
			GoodsList
		},
		data() {
			return {
				disabled: false,
				btnWidth: 180,
				show: false,
				options: [
					{
						text: '删除',
						style: {
							backgroundColor: '#dd524d'
						}
					}
				],
				queryParams: {},
				page: {
					currentPage: 1,
					pageSize: 80,
					descs: 'create_time',
				},
				isLoad: true,
				theme: getApp().globalData.theme,
				shoppingCartList: [],
				selectedValue: [], // 选中数据
				checkedAll: false, //是否全选
				totalPrice: 0,
				shoppingCart: {},
				goodsSpu: null,
				skuModal: false,
				showCreateOrder: true,
				selectedSku: {
					sku: []
				},
				effectiveGoodsIds: 0, //有效商品id
				isShow: false,
				isEdit: false,
				goodsSpuList: [], //推荐商品
				modelTpye: '' //1:都显示  2:只显示购物车 3:只显示立即购买 4:显示缺货按钮 默认 1
			}
		},
		computed: {
		    selectedValueLength() {
		        return this.selectedValue.length;
		    }
		},
		onLoad() {
		  this.getGoodsList();
		  
		  // 在安卓端时执行逻辑
		  if (process.env.VUE_APP_PLATFORM === 'android') {
		    this.$nextTick(() => {
		      this.$refs.checkboxGroup.$on('change', (value) => {
		        if (value.length === 0) {
		          // Checkbox 取消选中时添加样式
		          document.querySelector('.uni-checkbox-input').classList.add('uni-checkbox-input-not-checked');
		        } else {
		          // Checkbox 重新选中时移除样式
		          document.querySelector('.uni-checkbox-input').classList.remove('uni-checkbox-input-not-checked');
		        }
		      });
		    });
		  }
		},

		onShow() {
			getApp().initPage().then(res => {
				this.getPage();
			})
		    // 从本地存储中获取之前保存的选中状态数据
		     let selectedValueList = store.getters.goodsList
			 
			 // let shoppCount = uni.getStorageSync('shoppCountL')
			 
			// console.log(selectedValueNum + '选中')
			
		   
			 // console.log(this.shoppingCartList)
		   
		  //    console.log(shoppCount)
			 
			
		},
		watch: {
			selectedValue(val) {
				if (this.selectedValue.length > 0) {
					this.showCreateOrder = false;
				} else {
					this.showCreateOrder = true;
				}
			},
			isEdit(val) {
				if (!val) {
					// this.shoppingCartList.forEach(item => {
					// 	item.checked = false;
					// })
					// this.checkedAll = false;
					this.multiplex()
					
					
				} else {
					this.checkedAll = false;
					if (this.shoppingCartList.length == this.selectedValue.length) {
						this.checkedAll = true;
					}
					
					this.multiplex()
					
					// let selectedItemsData = [];
					// this.selectedValue.forEach(item=>{
						
					// 	const seleItem = this.shoppingCartList.filter( x => x.id == item)
					// 	selectedItemsData.push(...seleItem)
						
					// })
					
					// const totalPrice = selectedItemsData.reduce((acc, cur) => {
					//   return acc + (cur.goodsSku.costPrice * cur.quantity);
					// }, 0);
					// console.log(totalPrice); // 打印总价
					// this.totalPrice = totalPrice; // 将总价赋值给组件中的变量
					
				}
			}
		},
		methods: {
			multiplex(){
				let selectedItemsData = [];
				this.selectedValue.forEach(item=>{
					
					const seleItem = this.shoppingCartList.filter( x => x.id == item)
					selectedItemsData.push(...seleItem)
					
				})
				
				const totalPrice = selectedItemsData.reduce((acc, cur) => {
				  return acc + (cur.goodsSku.costPrice * cur.quantity);
				}, 0);
				console.log(totalPrice); // 打印总价
				this.totalPrice = totalPrice; // 将总价赋值给组件中的变量
			},
			// 如果打开一个的时候，不需要关闭其他，则无需实现本方法
			open(index) {
				// 先将正在被操作的swipeAction标记为打开状态，否则由于props的特性限制，
				// 原本为'false'，再次设置为'false'会无效
				this.shoppingCartList[index].show = true;
				this.shoppingCartList.map((val, idx) => {
					if(index != idx) this.shoppingCartList[idx].show = false;
				})
			},
			clickDele : debounce(function(index){
				let indexArr = []
				indexArr.push(index.id)
				shoppingCartDel(indexArr).then(res => {
					this.getPage();
					this.getCountNum()
				})
			},600),
			async getCountNum(){
				const { data } = await getCount()
				this.total = data
				console.log(data + '-----------')
			},
			toggleEditMode(){
				this.isEdit = !this.isEdit
				console.log(this.selectedValue.length)
			},
			routerLink(item){
				// :url="'/pages/goods/goods-detail/index?id=' + item.spuId"
				// console.log(item.goodsSpu.categorySecondId + '-------')
				if(item.goodsSpu.categorySecondId === "1498510397314220034"){
					uni.navigateTo({
						url:`/subpkg/beauty/beautyDetails/beautyDetails?id=${item.spuId}`
					})
				}else{
					uni.navigateTo({
						url:`/subpkg/goods/goods-detail/index?id=${item.spuId}`
					})
				}
				
			},
			//查询购物车商品列表
			getPage() {
				getShoppingCartPage({
					current: this.page.currentPage,
					size: this.page.pageSize,
					descs: this.page.descs
				}).then(res => {
					res.data.records.forEach(item => {
						item.checked = false;
					})
					this.checkedAll = false;
					this.totalPrice = 0;
					this.selectedValue = []
					// let shoppCount = uni.getStorageSync('shoppCountL')
					this.shoppingCartList = res.data.records.map(item => {
					  return { ...item, show: false }; // 将原始元素展开到一个新对象中，并添加一个新属性
					});
					
					
					console.log(this.selectedValue)
					
					this.effectiveGoodsIds = this.shoppingCartList.filter(item => item.goodsSku && item.goodsSku
							.stock > 0)
						.map(
							item => {
								return item.id
							});
				});
			},
			/**
			 * 购物车数量改变
			 */
			numberBoxChange(e) {
				this.$nextTick(() => {
				  this.addCart(e)
				
				//   let selectedValueNum = this.shoppingCartList.filter(item => {
				//     return this.selectedValue.includes(item.id);
				//   })
				//   if (this.shoppingCartList.length == this.selectedValue.length) {
				//     this.checkedAll = true
				//   }
				
				//   console.log(selectedValueNum)
				//   console.log(this.shoppingCartList)
				})

				
				
			},
			/**
			 * 数量修改
			 */
			addCart(dataObj) {
				let data = {
					id: dataObj.id,
					quantity: dataObj.quantity,
				};
				let that = this;
				shoppingCartEdit(data).then(res => {
					that.getPage();
					
				})

			},
			// 购物车全选
			changeShoppingCartAll(e) {
				this.checkedAll = !this.checkedAll;
				this.selectedValue = [];
				if (e.detail.value.length > 0) {
					if (this.isEdit) {
						this.selectedValue = this.shoppingCartList.map(
							item => {
								return item.id
							});
					} else {
						this.selectedValue = this.effectiveGoodsIds;
					}
				}
				this.goodsSum();
			},
			// 计算购物车选中商品金额
			goodsSum() {
				var items = this.shoppingCartList,
					values = this.selectedValue;
				this.checkedAll = false;
				// 不是编辑 只能选择有库存商品计算金额
				if (!this.isEdit) {
					let totalPrice = 0;
					items.forEach(item => {
						item.checked = false;
						if (values.indexOf(item.id) > -1 && item.goodsSku && item.quantity <= item
							.goodsSku.stock) {
							totalPrice = Number(totalPrice) + Number(item.quantity) * Number(item
								.goodsSku.salesPrice);
							item.checked = true;
						}
					})
					this.totalPrice = totalPrice.toFixed(2);
					// 如果可购买商品数量等于已勾选数量 设置全选按钮为true
					if (this.effectiveGoodsIds.length == values
						.length) {
						this.checkedAll = true;
					}
				} else { // 编辑所有商品可以选择
					items.forEach(item => {
						item.checked = false;
						if (values.indexOf(item.id) > -1) {
							item.checked = true;
						}
					})
					if (items.length == values
						.length) {
						this.checkedAll = true;
					}
				}				
			},
			//下单
			buySub() {
				if (this.shoppingCartList.length > 50) {
					uni.showToast({
						title: '最多只能为50个宝贝下单',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				if (this.shoppingCartList.length === 0) {
					uni.showToast({
						title: '请添加商品在进行购买',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				let goodsList = []
				this.shoppingCartList.forEach(function(shoppingCart, index) {
					if (shoppingCart.checked && shoppingCart.goodsSku && shoppingCart.goodsSku.enable == '1' &&
						shoppingCart.goodsSpu &&
						shoppingCart.goodsSpu.status == '1' && shoppingCart.quantity <= shoppingCart.goodsSku.stock
					) {
						let param = {
							spuId: shoppingCart.spuId,
							skuId: shoppingCart.skuId,
							quantity: shoppingCart.quantity,
							salesPrice: shoppingCart.goodsSku.salesPrice,
							spuName: shoppingCart.goodsSpu.name,
							specsInfo: shoppingCart.specsInfo,
							picUrl: shoppingCart.picUrl ? shoppingCart.picUrl : shoppingCart
								.goodsSpu.spuUrls[0],
							freightTemplate: shoppingCart.goodsSpu.freightTemplate,
							subscribeTime:shoppingCart.subscribeTime
						};
						
						goodsList.push(param);
					}
				});
				store.commit('SET_GOODS_LIST', goodsList);
				// store.commit('SET_ERROR_SHOPP', goodsList);
				uni.navigateTo({
					// url: '/pages/order/order-confirm/index',
					url: `/subpkg/order/order-confirm/index?type=${'1'}`,
				});
			},
			/**
			 * 打开sku
			 */
			openGoodsSku(row) {
				this.isShow = false;
				this.shoppingCart = row;
				this.getSpu(row.spuId);
				let sku = [];
				row.goodsSku.goodsSkuSpecsValues.forEach(item => {
					sku.push(item.specsValueId);
				})
				this.selectedSku.sku = sku;
				this.selectedSku.num = row.quantity;
				this.selectedSku.specsInfo = row.specsInfo;
				this.modelTpye = 2;
				this.skuModal = true;

			},
			// 查询商品信息
			getSpu(id) {
				goodsSpuById(id).then(res => {
					this.goodsSpu = res.data;
					this.isShow = true;
				});
			},
			// 删除商品
			delGoods() {
				if (this.selectedValue.length > 0) {
					shoppingCartDel(this.selectedValue).then(res => {
						this.getPage();
						this.getCountNum()
					})
				}else{
					uni.showToast({
						title: '还没有选择商品',
						icon: 'none',
						duration: 3000
					});
				}
			},
			checkboxChange(e) {
				this.selectedValue = e.detail.value;
				this.goodsSum();
			},
			// 查询推荐商品列表
			getGoodsList() {
				goodsSpuPage({
					current: 1,
					size: 10,
					descs: 'sales_volume'
				}).then(res => {
					this.goodsSpuList = res.data.records;
				});
			},
			skuClose(data) {
				this.getPage();

			},
		}
	}
</script>

<style lang="scss">
	/* 安卓平台下的Checkbox选中状态样式 */
	/* #ifdef APP-PLUS */
	
		uni-checkbox .uni-checkbox-input {
			transform: scale(1.1);
		}
	
		uni-checkbox .uni-checkbox-input.uni-checkbox-input-checked {
			border: 1rpx solid #007aff;
			background-color: #007aff;
		}
	
		uni-checkbox .uni-checkbox-wrapper {
			width: 100%;
		}
	
		uni-checkbox .uni-checkbox-input.uni-checkbox-input-checked:before {
			color: #FFF;
		}
	
		
	
		uni-checkbox .uni-checkbox-input:not(.uni-checkbox-input-checked) {
		  border: 1rpx solid #007aff;
		  background-color: #ffffff;
		}
	
	/* #endif */
	
	/* #ifdef MP-WEIXIN */
		
		checkbox .wx-checkbox-input {
			border-radius: 50%;
			border-color: #AAAAAA !important;
		}
		
		
		checkbox .wx-checkbox-input.wx-checkbox-input-checked {
			background: #007aff !important;
			border-color: #007aff !important;
			color: #fff;
		}
	/* #endif */
	
	::v-deep .uni-checkbox-input-checked{ 
		background-color: #007aff;
	}
	.shopping-cart {
		position: relative;
	}

	.out-stock {
		position: absolute;
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		background: rgba(0, 0, 0, 0.8);
	}

	.cu-card-before::before {
		background-color: #F2F3F5;
		opacity: 0.3;
		position: absolute;
		top: 0;
		right: 0;
		left: 0;
		bottom: 0;
		content: "";
		z-index: 1
	}
</style>
